package com.pap.oauth.config.exception.oauth;

import com.pap.obj.vo.response.ResponseVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * 自定义spring security oauth /auth/token的返回内容格式
 *
 * 因为 /oauth/token 的返回值格式与约定不同，这里可以增加切面，将其返回值进行额外处理，增加包装。
 */
@Component
@Aspect
public class AuthTokenAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        ResponseVO<OAuth2AccessToken> response = new ResponseVO<OAuth2AccessToken>();
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                response.setCode("200");
                response.setData(body);
            } else {
                response.setCode("600");
                response.setMsg("授权失败!");
            }
        }
        return ResponseEntity
                .status(200)
                .body(response);
    }
}